//
//  CYOAuthViewController.swift
//  WeiBo
//
//  Created by Mr_J on 16/3/5.
//  Copyright © 2016年 mac. All rights reserved.
//

import UIKit
import SVProgressHUD

//APPKEY = 3782997027

let CY_APPKEY = "3782997027"
let CY_REDIRECT_URL = "https://www.baidu.com/"
let CY_APPSECRET = "27b827ebb69e9cee419131b3f29f291b"

class CYOAuthViewController: UIViewController {

    private lazy var OAuthUrlStr = "https://api.weibo.com/oauth2/authorize?client_id=3782997027&redirect_uri=https://www.baidu.com/"
    
    override func loadView() {
        
        view = webView
        
        let request = NSURLRequest(URL: NSURL(string:OAuthUrlStr)!)
        
        webView.loadRequest(request)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        setItemButton()
    }
    
    private func setItemButton() {
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", target: self, action: "Back")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", target: self, action: "autofill")
        navigationItem.title = "新浪微博"
    }
    
   @objc private func Back(){
        dismissViewControllerAnimated(true, completion: nil)
    }
    
   @objc private func autofill() {
//        print("自动输入账号密码")
        let jsString = "document.getElementById('userId').value='76244604@qq.com';document.getElementById('passwd').value='zhaojian'"
        webView.stringByEvaluatingJavaScriptFromString(jsString)
    }
    
    private lazy var webView: UIWebView = {
        let webView = UIWebView()
        
        webView.delegate = self
        return webView
        }()
    
}

extension CYOAuthViewController :UIWebViewDelegate {
    
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        guard let url = request.URL else {
            return true
        }
        
        let urlStr = url.absoluteString
        
//        print(urlStr)
//        print(url)
        
        if urlStr.hasPrefix(CY_REDIRECT_URL) {
            print(urlStr.hasPrefix(CY_REDIRECT_URL))
            
            let query = url.query!
            
            let code = query.substringFromIndex("code=".endIndex)
//            print(code)
//            loadAccessToken(code)
            
            CYUserAccountViewModel.sharedAccountViewModel.loadAccessToken(code, callBack: { (isSuccess) -> () in
                if isSuccess {
                    self.dismissViewControllerAnimated(false, completion: { () -> Void in
                        print("登陆成功，跳转界面")
//                        
//                        let delegate = UIApplication.sharedApplication().delegate! as! AppDelegate
//                        print(delegate)
//                        let window = delegate.window
//                        window?.rootViewController = CYWelcomeViewController()
                        NSNotificationCenter.defaultCenter().postNotificationName("Cyr", object: self)
                    })
                    
                }else {
                    SVProgressHUD.showErrorWithStatus("由于某些原因登陆失败")
                }
                
            })
            
            
            
            return false
        }
        
        
        return true
        
    }
    
    
//    private func loadAccessToken(code: String) {
//        
//        let urlString = "https://api.weibo.com/oauth2/access_token"
//        
//        let parameters = [
//        
//            "client_id": CY_APPKEY,
//            "client_secret": CY_APPSECRET,
//            "grant_type": "authorization_code",
//            "code": code,
//            "redirect_uri":CY_REDIRECT_URL
//            
//        ]
//        
//        CYNetworkTools.sharedTools.requst(.POST, urlString: urlString, parameters: parameters) { (responseObject, error) -> () in
//            
//            if error != nil {
//                print("\(error)")
//                return
//            }
//            print(responseObject)
//            
//            let account = CYUserAccount(dict: responseObject!)
//            print("Cyr:\(account)")
//      
//            self.loadUserInfo(account)
//        }
//    
//    }
// 
//    private func loadUserInfo(account:CYUserAccount) {
//        
//        let urlStr = "https://api.weibo.com/2/users/show.json"
//        
//        guard let accessToken = account.access_token,uid = account.uid else {
//            print("参数不够")
//            return
//        }
//        
//        let parameters = [
//        
//            "access_token": accessToken,
//            "uid": uid
//        
//        ]
//
//        CYNetworkTools.sharedTools.requst(.GET, urlString: urlStr, parameters: parameters) { (responseObject, error) -> () in
//            
//            if error != nil {
//                print("个人信息请求错误")
//                SVProgressHUD.showErrorWithStatus("个人信息请求错误")
//                return
//            }
//            print(responseObject)
//            account.screen_name = responseObject!["screen_name"] as? String
//            account.avatar_large = responseObject!["avatar_large"] as? String
//            
//            let file = (NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask,true).last! as NSString).stringByAppendingPathComponent("account.archive")
//            print(file)
//            
//            NSKeyedArchiver.archiveRootObject(account, toFile: file)
//            
//        }
//        
//    }
//    
//    
    
}


